<script setup>
import {ref} from "vue";
import {updatePwd} from "@/api/user";
import {ElMessage} from "element-plus";
import {useUserInfoStore} from "@/stores/userInfo";
import router from "@/router";
const userInfo =  useUserInfoStore()
const formData = ref({
  password: '',
  newPassword:'',
  rePassword:''
})
const form = ref(null)
const checkPwd = (rule, value, callback) => {
  if (value === '') {
    callback(new Error("请输入确认密码"))
  }else if (value !== formData.value.newPassword) {
    callback(new Error("两次密码不一样"));
  } else {
    callback()
  }
}
const rules = {
  password: [
    {required: true, message: '请输入旧密码', trigger: 'blur'},
    {min: 5, max: 16, message: '长度为5-16位', trigger: 'blur'},
  ],
  newPassword:[
    {required: true, message: '请输入新密码', trigger: 'blur'},
    {min: 5, max: 16, message: '长度为5-16位', trigger: 'blur'},
  ],
  rePassword:[
    {required: true, message: '请输入确认密码', trigger: 'blur'},
    {validator:checkPwd,trigger: 'blur'}
  ]
}
const update =()=>{
  form.value.validate(valid=>{
    if (valid) {
      updatePwd(formData.value).then(res =>{
        if (res.status) {
          ElMessage.success("修改成功")
          userInfo.removeUserInfo()
          router.push("/login")
        } else {
          ElMessage.error(res.message)
        }
      })
    }
  })
}
</script>

<template>
  <el-card >
    <template #header>
      <div class="card-header">
        <span>重置密码</span>
      </div>
    </template>
    <el-row>
      <el-col :span="8" >
        <el-form ref="form" :model="formData" :rules="rules" label-width="100px">
          <el-form-item prop="password" label="旧密码">
            <el-input type="password" placeholder="请输入旧密码"
                      v-model="formData.password"></el-input>
          </el-form-item>
          <el-form-item prop="newPassword" label="新密码">
            <el-input type="password" placeholder="请输入新密码"
                      v-model="formData.newPassword"></el-input>
          </el-form-item>
          <el-form-item prop="rePassword" label="确认新密码">
            <el-input type="password" placeholder="请输入新密码"
                      v-model="formData.rePassword"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="update">提交修改</el-button>
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>

    <template #footer>Footer content</template>
  </el-card>
</template>

<style scoped lang="scss">

</style>